<template>
  <div>
    <div class="header">
      <div class="inputItem">
        <div class="title">全部状态</div>
        <div class="inputBox">
          <el-select class="select" v-model="steelState" placeholder="请选择">
            <el-option v-for="item in SettlementStatusArr" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="inputItem">
        <div class="title">结算单号</div>
        <div class="inputBox">
          <el-input v-model="steelNumber" @keyup.enter.native="searchHttpList(1)">
          </el-input>
        </div>
      </div>
      <div class="inputItem">
        <div class="title">货源方</div>
        <div class="inputBox">
          <el-input v-model="ownerName" @keyup.enter.native="searchHttpList(1)">
          </el-input>
        </div>
      </div>
      <div class="inputItem">
        <div class="title">项目名称</div>
        <el-select ref="projectNameRef1" clearable v-model="projectName" size="small" filterable placeholder="请选择"
          @change="changeProjectName($event)">
          <el-option v-for="item in projectNameOptions" :key="item.projectId" :label="item.name" :value="item.projectId">
          </el-option>
        </el-select>
      </div>
      <div class="inputItem">
        <div class="title">车队名称</div>
        <div class="inputBox">
          <el-input v-model="fleetName" @keyup.enter.native="searchHttpList(1)">
          </el-input>
        </div>
      </div>
      <div class="inputItem">
        <div class="title">创建时间</div>
        <el-date-picker size="small" v-model="createTime" type="datetimerange" :picker-options="pickerOptions"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </div>
      <!-- 查询 -->
      <div class="Btn_grounp">
        <el-button class="searchBtn" type="primary" size="small" icon="el-icon-search"
          @click="searchHttpList(1)">查询</el-button>
        <el-button class="clearBtn" type="plain" size="small" icon="el-icon-refresh-right" @click="CleanUp">清空</el-button>
      </div>
    </div>
    <div class="main">
      <div class="list">
        <el-table :data="records" style="width: 100%" ref="table1">
          <el-table-column align="center" prop="SerialNumber" label="序号" width="60">
          </el-table-column>
          <el-table-column align="center" prop="transportStatus" label="结算单状态" width="110">
            <template slot-scope="scope">
              <div style="display: flex; justify-content: center">
                <div class="tag" v-if="scope.row.steelState == 1">
                  <div class="dian"></div>
                  <div class="text">已结算</div>
                </div>
                <div class="tag yellow" v-else-if="scope.row.steelState == 0">
                  <div class="dian"></div>
                  <div class="text">未结算</div>
                </div>
                <div class="tag Canceled" v-else-if="scope.row.steelState == 2">
                  <div class="dian"></div>
                  <div class="text">已取消</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="steelNumber" label="结算单号" width="220">
          </el-table-column>
          <el-table-column align="center" prop="ownerName" label="货源方">
          </el-table-column>
          <el-table-column align="center" prop="projectName" label="项目名称">
          </el-table-column>
          <!--          <el-table-column-->
          <!--            align="center"-->
          <!--            prop="steelType.info"-->
          <!--            label="业务类型"-->
          <!--          >-->
          <!--          </el-table-column>-->
          <el-table-column align="center" prop="fleetName" label="车队名称">
          </el-table-column>
          <el-table-column align="center" prop="supplierMoney" label="货主金额">
          </el-table-column>
          <el-table-column align="center" prop="" label="结算金额">
            <template slot-scope="scope">
              <div v-if="scope.row.payAmount != undefined">
                {{
                  scope.row.steelState == 1
                  ? scope.row.payAmount
                  : scope.row.payAmount == 0
                    ? "--.--"
                    : scope.row.payAmount
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间" sortable width="160">
          </el-table-column>

          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <div>
                <el-button type="text" size="small" @click="
                $router.push(
                  '/home/selfOperatedSettlement/receiptDetails/' +
                  scope.row.fleetSteelOrderId
                )
                  ">详情</el-button>
                <el-button v-if="scope.row.steelState == 0" type="text" size="small"
                  @click="collection(scope.row)">结算</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="paginationBox">
        <el-pagination class="pagination" background layout="slot,prev, pager, next" :total="data.total * 1"
          :page-size="data.size * 1" :pager-count="5" @current-change="changePages($event)">
          <template slot>
            <span style="
                color: #686868;
                font-size: 12px;
                margin-right: 20px;
                display: inline-block;
              ">共{{ data.total }}条,每页{{ data.size }}条</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog class="CollectionDialog" title="车队结算" :visible.sync="dialogVisible" width="400px">
      <el-form :model="CollectionForm" :rules="CollectionRules" ref="CollectionForm" label-width="100px" class="demoForm">
        <el-form-item label="应付金额" prop="payableAmount">
          <el-input v-model="CollectionForm.payableAmount" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="实付金额" prop="payAmount">
          <el-input v-model="CollectionForm.payAmount" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input type="textarea" resize="none" :rows="2" placeholder="请输入内容" v-model="CollectionForm.notes">
          </el-input>
        </el-form-item>

        <el-form-item label="上传附件" prop="signImage">
          <!-- action	必选参数，上传的地址 -->
          <!-- on-preview	点击文件列表中已上传的文件时的钩子 -->
          <!-- on-remove	文件列表移除文件时的钩子 -->
          <!-- before-remove	删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。 -->

          <!-- limit	最大允许上传个数 -->
          <!-- on-exceed	文件超出个数限制时的钩子 -->
          <!-- file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] -->
          <el-upload class="upload" :action="url" :on-preview="handlePreview" :on-remove="handleRemove"
            :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed" :on-success="onSuccess"
            :file-list="fileList" :headers="headers" v-model="CollectionForm.annex">
            <el-button size="small" class="uploadBtn" type="primary">选择文件</el-button>
            <span slot="tip" class="el-upload__tip">
              仅可上传一份合同文件，支持PDF、JPG等格式
            </span>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <div class="BtnBox">
            <el-button class="Btn" @click="dialogVisible = false">取消</el-button>
            <el-button class="Btn" type="primary" @click="submitForm()">确定</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import httpApi from "@/http";
import BASEURL from "@/http/BaseUrl";
export default {
  data() {
    let validatePayRule = (rule, value, callback) => {
      let regular = /^([1-9]\d*(\.\d*[1-9][0-9])?)|^(0\.\d*[1-9][0-9])$|^(0\.\d*[1-9])$/

      if (value == '') {
        callback(new Error('金额不能为空'))
      } else if (value.split('.').length > 2) {
        callback('只能有一个小数点')
      } else if (!regular.test(value)) {
        callback(new Error('请输入正确面额金额'))
      } else {
        callback()
      }
    };
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      createTime: [],
      dialogVisible: false,
      fileList: [], //上传文件
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      url: BASEURL.TCHYURL + "/file/upload",
      CollectionForm: {
        notes: "",
        payableAmount: "",
        payAmount: "",
        annex: "",
      },
      CollectionRules: {
        payAmount: [{
          validator: validatePayRule,
          trigger: "blur",
        }],
      },
      steelState: "", //运单状态
      steelNumber: "", //运单编号
      projectName: "", //项目名称
      projectNameOptions: [],
      fleetName: "", //车队名称
      ownerName: "",
      TypeSelected: "",
      SerialNumber: "",
      records: [],
      data: {},
      pageCurrent: "1",
      size: "15",
      //全部状态选项
      SettlementStatusArr: [
        { value: "", label: "全部状态" },
        { value: "1", label: "已结算" },
        { value: "0", label: "未结算" },
        // { value: "2", label: "已取消" },
      ],
      //   业务类型选项
      BusinessTypeArr: [
        { value: "1", label: "无需配送" },
        { value: "2", label: "未发货" },
        { value: "3", label: "部分发货" },
        { value: "4", label: "已发货" },
        { value: "5", label: "待装运" },
        { value: "6", label: "装运完成" },
        { value: "7", label: "运输中" },
        { value: "8", label: "已送达" },
        { value: "9", label: "完成卸货" },
      ],
      selectObj: {},
    };
  },
  methods: {
    changePages(val) {
      this.pageCurrent = val;
      this.searchHttpList();
    },
    initList() {
      // status判定 2:已完成运单, 1:在途运单, 0:待审核运单
      let params = {
        current: this.pageCurrent,
        size: this.size,
		counterparty:1
      };
      httpApi.selfOperatedSettlementApi.getReceiptList(params).then((res) => {
        ////console.log(res);
        this.data = res.data.data;
        this.records = res.data.data.records;
        ////console.log("收款单总数据", this.data);
        ////console.log("收款单列表数据", this.records);
        this.records.forEach((item, i) => {
          let num = i + 1 + Number(this.size) * (this.pageCurrent - 1);
          item.SerialNumber = num;
        });
      });
    },
    searchHttpList(current) {
      let params = {
        current: current || this.pageCurrent,
        size: this.size,
        steelState: this.steelState,
        steelNumber: this.steelNumber,
        projectName: this.projectName,
        fleetName: this.fleetName,
        ownerName: this.ownerName,
        startTime: this.createTime != null ? this.createTime[0] : '', //开始时间
        endTime: this.createTime != null ? this.createTime[1] : '', //结束时间
		counterparty:1
      };
      httpApi.selfOperatedSettlementApi.getReceiptList(params).then((res) => {
        ////console.log(res);
        this.data = res.data.data;
        this.records = res.data.data.records;
        this.records.forEach((item, i) => {
          let num = i + 1 + Number(this.size) * (this.pageCurrent - 1);
          item.SerialNumber = num;
        });
        ////console.log("收款单总数据", this.data);
        ////console.log("收款单列表数据", this.records[0].fleetSteelOrderId);
      });
    },
    changeProjectName() {
      this.$nextTick(function () {
        this.projectName = this.$refs.projectNameRef1.selected.label
        this.projectId = this.$refs.projectNameRef1.selected.value
        //console.log(this.projectName, this.projectId)

      });
    },

    CleanUp() {
      this.steelState = "";
      this.projectId="";
      this.steelNumber = "";
      this.projectName = "";
      this.ownerName = ""
      this.fleetName = "";
      this.createTime = []
      this.searchHttpList(1);
    },
    handleRemove(file, fileList) {
      ////console.log(file, fileList);
      this.fileList = [];
    },
    handlePreview(file) {
      ////console.log(file, 3333);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    onSuccess(response, file, fileList) {
      ////console.log(response);
      this.CollectionForm.annex = response.data.url;
      this.fileList.push({
        name: response.data.name,
        url: this.url,
      });
    },
    collection(val) {
      this.CollectionForm = {
        notes: "",
        payableAmount: "",
        payAmount: "",
        annex: "",
      };
      this.fileList = [];
      this.dialogVisible = true;
      this.selectObj = val;
      this.CollectionForm.payableAmount = val.orderAmount;
      this.CollectionForm.payAmount = val.orderAmount;
    },
    getProjectNameOptions() {
      httpApi.selfOperatedSettlementApi.selectProjectName({}).then(res => {
        if (res.data.code == 200) {
          this.projectNameOptions = res.data.data
        }
      })
    },
    submitForm() {
      ////console.log(this.CollectionForm);
      // selectCollection
      let params = {
        fleetSteelOrderId: this.selectObj.fleetSteelOrderId,
        payAmount: this.CollectionForm.payAmount,
        remark: this.CollectionForm.notes,
        fileUrls: this.CollectionForm.annex,
      };
      httpApi.selfOperatedSettlementApi.selectCollection(params).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("付款成功");
          this.initList();
        }
      });
      this.dialogVisible = false;
    },
    // 记录滚动距离
    scrollEvent(res) {
      this.$route.meta.scrollTop = res.target.scrollTop
    },
  },
  activated() {
    //组件激活时监听表格滚动条位置,
    this.$refs.table1.bodyWrapper.addEventListener('scroll', this.scrollEvent, false)
    // 激活设置滚动位置
    this.$refs.table1.bodyWrapper.scrollTop = this.$route.meta.scrollTop
  },
  beforeRouteLeave(to, from, next) {
    // 为了节省资源，再离开页面的时候关闭对于scroll事件的监听
    this.$refs.table1.bodyWrapper.removeEventListener('scroll', this.scrollEvent)
    next()
  },



  mounted() {
    this.getProjectNameOptions()
    this.initList();
  },
};
</script>

<style lang="scss" scoped>
.header {
  // height: 76px;
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 10px 29px 0 29px;


  .Btn_grounp {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-bottom: 8px;


    .searchBtn {
      width: 80px;
      height: 32px;
      color: #fff;
      font-size: 12px;
    }

    .clearBtn {
      width: 80px;
      height: 32px;
      color: #262626;
      font-size: 12px;
    }
  }

  .inputItem {
    width: calc(100% / 3);
    display: flex;
    align-items: center;
    margin-bottom:10px;


    >.title {
      flex-shrink: 0;
      color: #262626;
      font-size: 12px;
      margin-right: 7px;
    }

    >.inputBox {
      width: 160px;

      .select {
        ::v-deep .el-input__icon {
          line-height: 0;
        }
      }

      ::v-deep .el-input__inner {
        height: 32px;
        font-size: 12px;
      }

      ::v-deep .el-input__inner::placeholder {
        color: #c3c3c3;
        font-size: 12px;
      }
    }
  }
}

.main {
  width: 100%;
  height: calc(100vh - 325px);
  background-color: #fff;
  padding: 0 30px 0 30px;

  .list {
    height: calc(100% - 48px);
    width: 100%;

    .tag {
      width: 63px;
      height: 28px;
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      background-color: #ecf5fe;
      color: #1890ff;

      &.yellow {
        background-color: #fffce8;
        color: #f9aa0d;

        .dian {
          background-color: #f9aa0d;
        }
      }

      &.Canceled {
        background-color: #fde8e9;
        color: #f5222d;

        .dian {
          background-color: #f5222d;
        }
      }

      .dian {
        width: 4px;
        height: 4px;
        border-radius: 50%;
        margin-right: 4px;
        background-color: #1890ff;
      }
    }

    ::v-deep .el-table__body-wrapper {
      height: calc(100vh - 422px);
      overflow-y: scroll;
    }

    // 表头样式
    ::v-deep .el-table__header th {
      background-color: #f0f6fd;
      color: #262626;
      font-size: 12px;
      font-weight: bold;
      text-align: center;
      padding: 0;
      height: 48px;

      // 表 body的td
      ::v-deep .el-table__body td {
        color: #595959;
        font-size: 12px;
      }
    }

    .stateBtns {
      height: 30px;
      width: 76px;

      ::v-deep .el-button {
        height: 30px;
        width: 76px;
        font-size: 12px;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
        line-height: 30px;
      }

      .waitPass {
        background-color: #ecf5fe;
        color: #1890ff;
      }

      .noPass {
        background-color: #fde8e9;
        color: #f7555d;
      }
    }
  }

  .paginationBox {
    width: 100%;
    background-color: #fff;
    display: flex;
    height: 48px;

    align-items: center;

    .pagination {
      height: 48px;
      display: flex;
      align-items: center;
      margin-left: auto;
    }
  }
}
</style>
